package com.yunqian.web;

import com.yunqian.constant.AliyunSmsKey;
import com.yunqian.exception.ActionException;
import com.yunqian.redot.domain.Code;
import com.yunqian.redot.service.CodeService;
import com.yunqian.util.RandomUtil;
import com.yunqian.util.message.AliyunSmsUtil;
import com.yunqian.util.validate.Validator;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Map;

/**
 * @author czy
 * @describe
 * @date 2018/8/27
 */
@Log4j2
@RestController
@RequestMapping("/sms/authCode")
public class SmsController {

    @Autowired
    private CodeService codeService;

    /**
     * 发送短信验证码
     *
     * @param params
     * @param request
     */
    @PostMapping
    public void sendMessage(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        String phone = (String) params.get("phone");
        if(Validator.isNull(phone)){
            throw new ActionException("手机号不能为空");
        }
        Calendar nowTime = Calendar.getInstance();
        // 当前时间减一分钟
        nowTime.add(Calendar.MINUTE, -1);
        Code codeObj = codeService.getFirstByPhone(phone);
        // 如果又记录并且上条记录时再前一分钟内，则不在发送验证码
        if(Validator.isNotNull(codeObj) && codeObj.getSaveTime().after(nowTime.getTime())){
            throw new ActionException("请求频繁，请稍后再试");
        }

        // 生成四位随机验证码
        String code = RandomUtil.messageCode();
        // 发送短信
        String templateParams = "{\"code\":\"" + code + "\"}";
        AliyunSmsUtil.sendSMSMessage(phone, templateParams, AliyunSmsKey.TEMPLATE_CODE);

        // 设置过期时间 5分钟
        nowTime.add(Calendar.MINUTE, 5);
        // 先删除上条记录
        if(Validator.isNotNull(codeObj)){
            codeService.delete(codeObj);
        }
        // 往数据库中存储code
        codeService.save(new Code(nowTime.getTime(), phone, code));
    }
}
